package com.ld.businesscard_manage.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.ld.businesscard_manage.bean.BusinessCard;
import com.ld.businesscard_manage.bean.Msg;
import com.ld.businesscard_manage.bean.User;
import com.ld.businesscard_manage.service.BusinessCardService;
import com.ld.businesscard_manage.service.UserService;
import com.ld.businesscard_manage.service.impl.BusinessCardServiceImpl;
import com.ld.businesscard_manage.service.impl.UserServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.List;

import static java.lang.System.out;

public class UploadDataListener implements ReadListener<BusinessCard> {

		/**
		 * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
		 */
		private static final int BATCH_COUNT = 100;
		/**
		 * 缓存的数据
		 */
		private List<BusinessCard> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
		/**
		 * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
		 */
		private BusinessCardService cardService;
		private UserService userService;

		public UploadDataListener() {
			// 这里是demo，所以随便new一个。实际使用如果到了spring,请使用下面的有参构造函数
			cardService = new BusinessCardServiceImpl();
			userService = new UserServiceImpl();
		}



		/**
		 * 这个每一条数据解析都会来调用
		 *
		 * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
		 * @param context
		 */
		@Override
		public void invoke(BusinessCard data, AnalysisContext context) {
			data.setPassword(DigestUtils.md5Hex(data.getPassword()));
			cachedDataList.add(data);
			// 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
			if (cachedDataList.size() >= BATCH_COUNT) {
				saveData();
				// 存储完成清理 list
				cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
			}
		}

		/**
		 * 所有数据解析完成了 都会来调用
		 *
		 * @param context
		 */
		@Override
		public void doAfterAllAnalysed(AnalysisContext context) {
			// 这里也要保存数据，确保最后遗留的数据也存储到数据库
			saveData();
		}

		/**
		 * 加上存储数据库
		 */
		private Msg saveData() {
			int all = 0;
			int success = 0;
			for (BusinessCard card : cachedDataList) {
				all ++;
				out.println(card.getAccount());
				User userByName = userService.getUserByName(card.getAccount());
				if (userByName != null) {
					if(userByName.getPassword().equals(DigestUtils.md5Hex(card.getPassword()))) {
						int i = cardService.addCard(card);
						success += i;
					}
				} else {
					User user = new User();
					user.setUsername(card.getAccount());
					user.setPassword(card.getPassword());
					user.setStatus(0);
					int j = userService.addUser(user);
					int i = cardService.addCard(card);
					if (i == 1 && j == 1) {
						success ++;
					}
				}

			}
			out.println("共插入" + all + "条数据");
			out.println("成功" + success + "条");
			return new Msg(all,success);
		}

}
